package com.elinkway.infinitemovies.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.Episode;
import com.elinkway.infinitemovies.download.DownloadEntity;
import com.elinkway.infinitemovies.download.DownloadJob;
import com.elinkway.infinitemovies.download.DownloadUtils;
import com.le123.ysdq.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DownLoadListAdapter extends BaseAdapter {

    private Context mContext;
    private LayoutInflater inflater;
    private ArrayList<Episode> episodes;
    private String site;

    // 用来控制item的选中状况
    private SparseArray<Boolean> isSelected;

    private String mdefaultClarity;
    // 用来控制item的清晰度是否存在
    private SparseArray<Boolean> isHasClarity;

    private class ItemHolder {
        TextView tv;
        TextView mPeriod;
        ImageView downloadIconIv;
        RelativeLayout ll;
    }

    public DownLoadListAdapter(Context mContext, ArrayList<Episode> episodes, String site) {
        super();
        this.mContext = mContext;
        this.episodes = episodes;
        this.inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        initData();
        this.isSelected = updateDownloadedFlagByDB(episodes, isSelected);
        this.site = site;
    }

    private void initData() {
        isSelected = new SparseArray<Boolean>();
        isHasClarity = new SparseArray<Boolean>();
        if (null != episodes && episodes.size() > 0) {
            for (int i = 0; i < episodes.size(); i++) {
                isSelected.put(i, false);
                isHasClarity.put(i, true);//默认存在
            }
        }

    }

    public void updateDownloadSelectStatus() {
        initData();
        this.isSelected = updateDownloadedFlagByDB(episodes, isSelected);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return episodes.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup arg2) {
        ItemHolder holder = new ItemHolder();
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.download_list_item, null);
            holder.tv = (TextView) convertView
                    .findViewById(R.id.episode_list_item_text);
            holder.mPeriod = (TextView) convertView.findViewById(R.id.periods);
            holder.ll = (RelativeLayout) convertView.findViewById(R.id.layout);
            holder.downloadIconIv = (ImageView) convertView.findViewById(R.id.episode_download_icon_iv);
            convertView.setTag(holder);
        } else {
            holder = (ItemHolder) convertView.getTag();
        }
        if (!TextUtils.isEmpty(episodes.get(position).getPorder())) {
            holder.mPeriod.setText(episodes.get(position).getPorder());
        }
        if (!TextUtils.isEmpty(episodes.get(position).getSubName())) {
            holder.tv.setText(episodes.get(position).getSubName());
        }
        setItemSelection(position, holder);
        return convertView;
    }

    public void setEpisodes(ArrayList<Episode> episodes, String site) {
        this.episodes = episodes;
        this.site = site;
        initData();
        this.isSelected = updateDownloadedFlagByDB(episodes, isSelected);
        notifyDataSetChanged();
    }

    /**
     * 清晰度切换，设置码流
     */
    public void setPls(String defaultClarity) {
        mdefaultClarity = defaultClarity;
        notifyDataSetChanged();
    }

    // 设置item项的选中状态（根据下载状态设置view显示）
    private void setItemSelection(int position, ItemHolder viewHolder) {
        if (null != isSelected && isSelected.size() > position) {
            if (isSelected.get(position)) {
                viewHolder.ll.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.rectangle_round_corner_3_selected));
                if (!TextUtils.isEmpty(episodes.get(position).getPorder())) {
                    viewHolder.mPeriod.setTextColor(mContext.getResources().getColor(R.color.color_3599f8));
                }
                if (!TextUtils.isEmpty(episodes.get(position).getSubName())) {
                    viewHolder.tv.setTextColor(mContext.getResources().getColor(R.color.color_3599f8));
                }
                viewHolder.downloadIconIv.setVisibility(View.VISIBLE);
            } else {
                viewHolder.ll.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.rectangle_round_corner_3));
                if (!TextUtils.isEmpty(episodes.get(position).getPorder())) {
                    viewHolder.mPeriod.setTextColor(mContext.getResources().getColor(R.color.color_666666));
                }
                if (!TextUtils.isEmpty(episodes.get(position).getSubName())) {
                    viewHolder.tv.setTextColor(mContext.getResources().getColor(R.color.color_666666));
                }
                viewHolder.downloadIconIv.setVisibility(View.INVISIBLE);
            }
        }
        //区分是否是乐视源
        if (!"letv".equals(site) && !"nets".equals(site) && !DownloadUtils.ISDOWNLOAD.equals(episodes.get(position).getIsdownload()) && !isSelected.get(position)) {
//            viewHolder.ll.setBackgroundResource(R.color.color_f8f8f8);
        } else if ("letv".equals(site)) {
            String pls = episodes.get(position).getPls();
            if (!TextUtils.isEmpty(pls) && !isSelected.get(position)) {
                String[] types = pls.split(",");
                List<String> typeList = Arrays.asList(types);
                if (null != mdefaultClarity && !typeList.contains(mdefaultClarity)) {
//                    viewHolder.tv.setBackgroundResource(R.color.color_f8f8f8);
                    isHasClarity.put(position, false);
                } else if (typeList.contains(mdefaultClarity)) {
//                    viewHolder.ll.setBackgroundResource(R.drawable.download_grid_selector);
                    isHasClarity.put(position, true);
                }
            }
        }
    }

    // 设置下载选中项(用户点击下载剧集列表)
    public void setSelectedItem(int position, View view) {
        ItemHolder viewHolder = (ItemHolder) view.getTag();
        if (null != isSelected && isSelected.size() > position) {
            if (isSelected.get(position)) {

            } else {
                viewHolder.ll.setBackgroundColor(mContext.getResources().getColor(R.color.color_f5faff));
                viewHolder.downloadIconIv.setVisibility(View.VISIBLE);
                isSelected.put(position, true);
            }
        }
    }

    // 设置下载选中项
    public void setSelectedAllItem(int position) {
        if (null != isSelected && isSelected.size() > position) {
            if (!isSelected.get(position)) {
                isSelected.put(position, true);
            }
        }
    }

    // 返回选中项是否已经在下载队列
    public boolean getIsSelected(int position) {
        boolean result = false;
        if (null != isSelected && isSelected.size() > position) {
            result = isSelected.get(position);

        }
        return result;
    }

    // 返回选中项是否存在对应的清晰度
    public boolean getIsHasClarity(int position) {
        boolean result = false;
        if (null != isHasClarity && isHasClarity.size() > position) {
            result = isHasClarity.get(position);

        }
        return result;
    }

    public SparseArray<Boolean> getIsSelected() {
        return isSelected;
    }

    public void setIsSelected(SparseArray<Boolean> isSelected) {
        this.isSelected = isSelected;
    }

    public void updateDownloadedFlag() {
        initData();
        updateDownloadedFlagByDB(episodes, isSelected);
    }

    // 根据下载数据库中的数据更新已下载标记
    public SparseArray<Boolean> updateDownloadedFlagByDB(ArrayList<Episode> episodeList, SparseArray<Boolean> isSelected) {
        ArrayList<DownloadJob> downloadList = MoviesApplication.getInstance()
                .getDownloadManager().getAllDownloads();
        if (null != downloadList && downloadList.size() > 0) {
            DownloadEntity entity;
            String downloadSerialsId;
            for (int i = 0; i < downloadList.size(); i++) {
                entity = downloadList.get(i).getEntity();
                if (null != entity) {
                    downloadSerialsId = entity.getId();
                    if (null != episodeList && episodeList.size() > 0 && !TextUtils.isEmpty(downloadSerialsId)) {
                        String serialId;
                        for (int j = 0; j < episodeList.size(); j++) {
                            serialId = episodeList.get(j).getSerialid();
                            if (downloadSerialsId.equals(serialId)) {
                                isSelected.put(j, true);
                            }
                        }
                    }
                }
            }
        }
        return isSelected;
    }

}
